package com.xhj.springbootproject.config;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author ：Xionghaijun
 * @date ：Created in 2019/8/15 8:53 AM
 * @description：
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //定制请求的授权规则
        http.authorizeRequests().antMatchers("/","/login").permitAll()
                .antMatchers("/level1/**").hasRole("V1")
                .antMatchers("/level2/**").hasRole("V2")
                .antMatchers("/level3/**").hasRole("V3")
                .and().formLogin().usernameParameter("userName").loginPage("/login");
        //开启自动配置的登录功能
        http.authorizeRequests().anyRequest().authenticated();
        //1.访问页面自动跳转到/login
        //2.登录失败自动重定向到/login?error
        //3.更多详情规定
//        http.formLogin().usernameParameter("userName").loginPage("/login").permitAll();

        //1.访问/logout表示用户注销，清空session
        //2.注销成功会返回/login?logout页面
        http.logout().logoutSuccessUrl("/").permitAll();    //注销成功后来到首页

        //开启记住我功能
        http.rememberMe();

    }

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("zhangsan").password("123456").roles("V1")
//                .and()
//                .withUser("lisi").password("123456").roles("V2", "V3")
//                .and()
//                .withUser("wangwu").password("123456").roles("V1", "V3")
//                .and()
//                .withUser("admin").password("admin123").roles("V1", "V2", "V3");
//    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        //设置静态资源不要拦截
        web.ignoring().antMatchers("/js/**","/css/**","/images/**");
    }
}
